<template>
  <view class="container">
    <!-- 增强型搜索栏 -->
    <view class="search-bar bg-white fixed-top">
      <uni-search-bar 
        v-model="searchQuery"
        placeholder="输入订单号/用户姓名搜索"
        cancel-button="none"
        bg-color="#FFFFFF"
        radius="34"
        clear-button="always"
        @input="handleSearchInput"
      >
        <template v-slot:searchIcon>
          <uni-icons type="search" size="18" color="#666" />
        </template>
      </uni-search-bar>
    </view>

    <!-- 智能筛选区 -->
    <view class="filter-section gradient-bg">
      <view class="total-count">
        <text class="count-num">{{ totalCount }}</text> 条结果
      </view>
      <view class="filter-group">
        <picker 
          @change="handleStatusChange"
          :value="selectedStatusIndex"
          :range="statusOptions"
          range-key="label"
          mode="selector"
        >
          <view class="filter-btn">
            {{ statusOptions[selectedStatusIndex].label }}
            <uni-icons type="arrowdown" size="12" color="#666" />
          </view>
        </picker>
      </view>
    </view>

    <!-- 优化后的订单列表 -->
    <scroll-view 
      class="order-list"
      scroll-y
      :show-scrollbar="false"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="handleRefresh"
      @scrolltolower="loadMore"
      :style="{ height: listHeight + 'px' }"
    >
      <!-- 自定义下拉刷新 -->
      <view class="custom-refresher" v-if="isRefreshing">
        <uni-icons type="spinner-cycle" size="24" color="#007AFF" class="refresh-icon" />
      </view>

      <!-- 卡片容器 -->
      <view 
        v-for="(order, index) in orders" 
        :key="order.id + '_' + index"
        class="order-card elevate-2"
        :class="{'card-hover': !isTouchDevice}"
      >
        <!-- 卡片头部 -->
        <view class="card-header">
          <view class="header-left">
            <text class="order-number">{{ order.orderNo }}</text>
            <text class="status-tag" :class="statusClass(order.status)">{{ statusText(order.status) }}</text>
          </view>
          <text class="order-amount">￥{{ order.amount.toFixed(2) }}</text>
        </view>

        <!-- 卡片主体 -->
        <view class="card-body">
          <view class="info-row">
            <uni-icons type="person" size="14" color="#007AFF" />
            <text class="info-text">{{ order.userName }}</text>
          </view>
          <view class="info-row">
            <uni-icons type="calendar" size="14" color="#34C759" />
            <text class="info-text">{{ formatDate(order.reserveTime) }}</text>
          </view>
          <view class="info-row service-row">
            <uni-icons type="cart" size="14" color="#FF9500" />
            <text class="service-name">{{ formatServiceInfo(order) }}</text>
          </view>
        </view>

        <!-- 卡片脚部 -->
        <view class="card-footer">
          <text class="order-time">{{ formatDateTime(order.createTime) }}</text>
          <button 
            class="detail-btn gradient-btn"
            :hover-class="isTouchDevice ? 'btn-hover' : ''"
            @click="viewDetail(order.id)"
          >
            详情
            <uni-icons type="right" size="14" color="#FFF" />
          </button>
        </view>
      </view>

      <!-- 加载状态 -->
      <uni-load-more 
        :status="loadingStatus"
        :icon-size="16"
        :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '正在加载',
          contentnomore: '没有更多数据了'
        }"
      />
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import request from '../../utils/request'

// 添加防抖函数实现
const debounce = (fn, delay = 500) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 设备检测（用于悬停效果兼容）
const isTouchDevice = ref(uni.getSystemInfoSync().platform !== 'devtools')

// 响应式数据
const searchQuery = ref('')
const selectedStatusIndex = ref(0)
const statusOptions = ref([{ label: '全部状态', value: null }])
const orders = ref([])
const loadingStatus = ref('more')
const isRefreshing = ref(false)
const listHeight = ref(0)
const currentPage = ref(1)
const pageSize = 10
const total = ref(0)


let mockDataPage = 1

// 日期格式化
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

const formatDateTime = (timestamp) => {
  const date = new Date(timestamp)
  return `${formatDate(timestamp)} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 状态显示
const statusText = (statusValue) => {
  const option = statusOptions.value.find(opt => opt.value === statusValue)
  return option ? option.label : '未知状态'
}

const statusClass = (statusValue) => {
  const statusMap = {
    0: 'status-pending',
    1: 'status-processing',
    2: 'status-completed',
    4: 'status-canceled'
  }
  return statusMap[statusValue] || ''
}

// 时间区间显示
const timePeriod = (timestamp) => {
  const hour = new Date(timestamp).getHours()
  if (hour < 6) return '凌晨'
  if (hour < 12) return '上午'
  if (hour < 14) return '中午'
  if (hour < 18) return '下午'
  return '晚上'
}


const totalCount = computed(() => orders.value.length)

// 生命周期
onMounted(async () => {
  await loadOrderCategories()
  loadData(true)
  calcListHeight()
})

const loadOrderCategories = async () => {
  try {
    const res = await request({
      url: '/system/dict/data/type/order_type',
      method: 'get'
    })
    
    if (res.code === 200) {
      statusOptions.value = [
        { label: '全部状态', value: null },
        ...res.data.map(item => ({
          label: item.dictLabel,
          value: parseInt(item.dictValue)
        }))
      ]
    }
  } catch (error) {
    console.error('加载订单类别失败:', error)
  }
}

const getAllOrder = async () =>{
	request({
		url: '/serviceItem/order/list',
		method: 'get',
		data: {
		    storeId: 1,
		    pageNum: reset ? 1 : currentPage.value,
		    pageSize: pageSize
		}
	})
}

const orderCategories = ref([])

// 新增服务信息格式化方法
const formatServiceInfo = (order) => {
  const parts = []
  if (order.serviceInfo.package) {
    parts.push(`套餐：${order.serviceInfo.package}`)
  }
  if (order.serviceInfo.services.length > 0) {
    parts.push(`服务：${order.serviceInfo.services.join('，')}`)
  }
  return parts.join(' | ') || '无服务项目'
}

onReady(() => {
  uni.$on('windowResize', calcListHeight)
})

// 方法
const calcListHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  const query = uni.createSelectorQuery()
  query.select('.filter-section').boundingClientRect()
  query.select('.search-bar').boundingClientRect()
  query.exec(res => {
    const filterHeight = res[0]?.height || 0
    const searchHeight = res[1]?.height || 0
    listHeight.value = systemInfo.windowHeight - filterHeight - searchHeight - 10
  })
}

const loadData = async (reset = false) => {
  if (reset) {
    currentPage.value = 1
    orders.value = []
  }

  loadingStatus.value = 'loading'

  try {
    const params = {
      storeId: 1, // 根据实际业务调整
      pageNum: currentPage.value,
      pageSize: pageSize,
      orderStatus: statusOptions.value[selectedStatusIndex.value].value || undefined,
      searchKey: searchQuery.value.trim() || undefined 
    }
	
	// 添加请求参数日志
	console.log('请求参数:', params)

    const res = await request({
      url: '/serviceItem/order/list',
      method: 'get',
      params
    })

    if (res.code === 200) {
      const data = res.data
      total.value = data.total

      const newOrders = data.rows.map(order => ({
        id: order.orderId,
        orderNo: order.orderId,
        amount: order.actualTotalAmount,
        userName: order.memberName,
        reserveTime: new Date(order.appointmentTime).getTime(),
        serviceInfo: {
              package: order.packageNames,
              services: order.serviceNames?.split(',') || []
            },
        createTime: new Date(order.orderTime).getTime(),
        status: order.orderStatus
      }))

      orders.value = reset ? newOrders : [...orders.value, ...newOrders]
      currentPage.value += 1
      loadingStatus.value = data.rows.length < pageSize ? 'noMore' : 'more'
    }
  } catch (error) {
    console.error('加载订单失败:', error)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    isRefreshing.value = false
  }
}

const handleSearchInput = debounce(() => loadData(true), 500)

const handleStatusChange = (e) => {
  selectedStatusIndex.value = e.detail.value
  // 添加状态变更日志
  console.log('当前筛选状态:', statusOptions.value[selectedStatusIndex.value])
  loadData(true)
}

const handleRefresh = () => {
  isRefreshing.value = true
  mockDataPage = 1
  loadData(true)
}

const loadMore = () => {
  if (loadingStatus.value !== 'more') return
  loadData()
}

const viewDetail = (orderId) => {
  uni.navigateTo({
    url: `/pages/order_detail/order_detail?id=${orderId}`,
    animationType: 'slide-in-right'
  })
}
</script>

<style lang="scss" scoped>
/* 基础样式 */
$primary-color: #007AFF;
$success-color: #34C759;
$warning-color: #FF9500;
$error-color: #FF3B30;

.container {
  background: #F5F5F9;
  min-height: 100vh;
}

.search-bar {
  z-index: 1000;
  padding: 16rpx 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  
  ::v-deep .uni-searchbar {
    padding: 0 !important;
  }
}

/* 筛选区域 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  background: linear-gradient(135deg, #FFFFFF 0%, #F8F9FA 100%);
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  
  .total-count {
    font-size: 28rpx;
    color: #666;
    
    .count-num {
      font-weight: 600;
      color: $primary-color;
      margin: 0 8rpx;
    }
  }
  
  .filter-btn {
    display: flex;
    align-items: center;
    padding: 12rpx 24rpx;
    background: rgba($primary-color, 0.1);
    border-radius: 48rpx;
    font-size: 26rpx;
    color: $primary-color;
    transition: all 0.2s;
    
    &:active {
      background: rgba($primary-color, 0.2);
    }
  }
}

/* 订单卡片 */
.order-card {
  margin: 24rpx 32rpx;
  background: #FFFFFF;
  border-radius: 24rpx;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  
  &.card-hover:hover {
    transform: translateY(-6rpx);
    box-shadow: 0 12rpx 24rpx rgba(0,0,0,0.12);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #F0F0F0;
    
    .header-left {
      flex: 1;
      margin-right: 24rpx;
    }
    
    .order-number {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
    
    .status-tag {
      display: inline-block;
      padding: 4rpx 16rpx;
      border-radius: 8rpx;
      font-size: 22rpx;
      margin-left: 16rpx;
      
      &.status-pending { background: rgba($warning-color, 0.1); color: $warning-color; }
      &.status-processing { background: rgba($primary-color, 0.1); color: $primary-color; }
      &.status-completed { background: rgba($success-color, 0.1); color: $success-color; }
      &.status-canceled { background: rgba($error-color, 0.1); color: $error-color; }
    }
    
    .order-amount {
      font-size: 36rpx;
      font-weight: 600;
      color: $primary-color;
    }
  }
  
  .card-body {
    padding: 32rpx;
    
    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;
      font-size: 28rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .uni-icons {
        margin-right: 12rpx;
      }
      
      .info-text {
        color: #666;
      }
      
      .time-badge {
        margin-left: 16rpx;
        padding: 4rpx 12rpx;
        background: rgba(#000, 0.05);
        border-radius: 8rpx;
        font-size: 24rpx;
        color: #888;
      }
    }
    
    .service-name {
      color: #333;
      font-weight: 500;
      position: relative;
      padding-left: 8rpx;
	  flex-wrap: wrap;
	  
	  > text {
	      margin-right: 12rpx;
	    }
		
		
      
      &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        height: 60%;
        width: 4rpx;
        background: $warning-color;
        border-radius: 2rpx;
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 32rpx;
    background: #F8F9FA;
    
    .order-time {
      font-size: 24rpx;
      color: #999;
    }
    
    .gradient-btn {
      background: linear-gradient(45deg, $primary-color, #0063CC);
      color: #FFF;
      padding: 1rpx 32rpx;
      border-radius: 40rpx;
      font-size: 26rpx;
      display: flex;
      align-items: center;
      box-shadow: 0 4rpx 12rpx rgba($primary-color, 0.2);
      
      .uni-icons {
        margin-left: 8rpx;
      }
      
      &.btn-hover:active {
        opacity: 0.9;
        transform: scale(0.96);
      }
    }
  }
}

/* 自定义下拉刷新 */
.custom-refresher {
  display: flex;
  justify-content: center;
  padding: 24rpx 0;
  
  .refresh-icon {
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式适配 */
@media (max-width: 480px) {
  .order-card {
    margin: 24rpx;
    border-radius: 16rpx;
    
    .card-header {
      padding: 24rpx;
    }
  }
}
</style>